const fs = require('fs');
const nodeUtil = require('util');
const express = require('express')
const {ObjectId} = require('mongodb')
const multer  = require('multer')

const util = require('../util')
const mongo = require('../db_helper')
const task = require('../task')
const { getStatus } = require('../service')

const upload = multer({ dest: 'public/upload/' })

const router = express.Router()
const logger = util.getLogger('router.index')
const unlink = nodeUtil.promisify(fs.unlink);   //删除文件

/**
 * 替换原有的 get|post 函数，由于原函数没有异常捕获，会出现
 */
function change (router, name){
  if (typeof(router[name]) === 'function'){
    router['__' + name] = router[name];
    router[name] = (url, ...fun) => {
      let lastCallBack = fun[fun.length - 1]    //最后一个回调函数为业务函数

      //重写业务函数
      fun[fun.length - 1] = async (req, res, next)=>{
        try{
          logger.debug(`请求的url：${url}，提交的 json：`, req.body)
          let json = await lastCallBack(req.body, req);
          res.json({
            head: util.sucResMsg,
            body: json
          });    //如果执行过写入响应操作，在此处可以结束，如果已经写入，此处再次写入将无效
        }catch(e){
          logger.error('error------>' ,e);
          res.json({
            head: util.getErrMsg('-99'),
            message: e.message,
            stack: e.stack
          });
          next();
        }
      }
      //执行原 express 函数
      router['__' + name](url, fun);
    }
  }
}

change(router, 'get');
change(router, 'post');

//接入新任务
router.post('/api/addjob', async (body) => {
  body.status = '1'
  let result = await mongo.jobs.insertOne(body)
  body._id = result.insertedId 
  task.addJob(body)   //将job加入到定时踌躇
  return {
    _id: result.insertedId
  }
})

//修改任务状态
router.post('/api/status', async (body) => {
  let result = await mongo.jobs.findOneAndUpdate({
    _id: new ObjectId(body._id)
  }, {
    $set: {
      status: body.status
    }
  })

  let job = result.value

  if (body.status === '1') {
    //添加job
    task.addJob(job)
  } else {
    //删除job
    task.remove(job)
  }

})

//删除任务
router.post('/api/delete', async (body) => {
  let result = await mongo.jobs.findOneAndDelete({_id: new ObjectId(body._id)})
  task.remove(result.value)
})

//修改任务
router.post('/api/editjob', async (body) => {
  let id = { _id: new ObjectId(body._id) }
  let result = await mongo.jobs.findOneAndUpdate(id, Object.assign({}, body, id))
  if (body.status === '1') {
    task.remove(result.value)
    task.addJob(body)
  }
})

//所有任务
router.post('/api/getall', async (body) => {
  let jobs = await mongo.jobs.find({}).toArray()
  // logger.debug('jobs: ', jobs)
  return jobs
})

//运行任务
router.post('/api/run', async (body) => {
  let job = await mongo.jobs.findOne({_id: new ObjectId(body._id)})
  task.runJob(job, 'admin')
})

// 任务运行测试
router.post('/api/test', async (body) => {
  
})

//查询日志
router.post('/api/log/all', async (body) => {
  let logs = await mongo.logs.find({})
    .sort({ beginTime: -1 })
    .limit(body.pageSize)
    .skip((body.pageNum - 1) * body.pageSize)
    .toArray()
  let total = await mongo.logs.count({})
  return {
    logs, total
  }
})

//查看 hdfs
router.post('/api/hdfs/ls', async (body) => {
  let out = await util.runExec(`hadoop fs -ls ${body.path}`)
  return out
})

//上传到hdfs
router.post('/api/hdfs/put', upload.single('file'), async (body, req) => {
  let hdfsPath = body.hdfsPath
  let filePath = req.file.path
  let commond = `hadoop fs -copyFromLocal ${filePath} ${hdfsPath}/${req.file.originalname}`
  try{
    let out = await util.runExec(commond)
    return out
  }catch(e){
    return {
      'hdfs-error': e.stack
    }
  }finally{
    logger.info('删除文件：' + filePath)
    unlink(filePath)
  }
})

//删除 hdfs
router.post('/api/hdfs/del', async (body) => {
  let out = await util.runExec(`hadoop fs -rm ${body.path}`)
  return out
})

//
router.post('/api/service', (body) => {
  return getStatus()
})

module.exports = router;
